package com.qkjia.srb.core.controller.api;

import com.alibaba.fastjson.JSON;
import com.qkjia.common.result.R;
import com.qkjia.srb.base.util.JwtUtils;
import com.qkjia.srb.core.hfb.RequestHelper;
import com.qkjia.srb.core.pojo.vo.UserBindVO;
import com.qkjia.srb.core.service.UserBindService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 *  @author 赵乾坤
 *  @since 2021-11-13 22:53
 * 网关解决跨域 不用注解
 */
@Api(tags = "会员账号绑定")
@RestController
@RequestMapping("/api/core/userBind")
@Slf4j
public class UserBindApiController {

    @Resource
    private UserBindService userBindService;


    /**
     * 需要 用户名同步信息所以拿token
     *
     * @param userBindVO 账户绑定页面
     * @return
     */
    @ApiOperation("账户绑定提交数据")
    @PostMapping("/auth/bind")
    public R bind(@RequestBody UserBindVO userBindVO, HttpServletRequest request){

        //从header中获取token，并对token进行校验，确保用户已登录，并从token中提取userId
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);

        //根据userId做账户绑定，生成一个动态表单的字符串
        String formStr = userBindService.commitBindUser(userBindVO, userId);
        return R.ok().data("formStr", formStr);
    }

    @ApiOperation("账户绑定异步回调")
    @PostMapping("/notify")
    public String notify(HttpServletRequest request) {
        // 取出传的参数
        Map<String, Object> paramMap = RequestHelper.switchMap(request.getParameterMap());
        log.info("用户账号绑定回调：" + JSON.toJSONString(paramMap));
        // 检验签名
        if (!RequestHelper.isSignEquals(paramMap)) {
            log.error("用户账号绑定异步回调签名失误：" + JSON.toJSONString(paramMap));
            return "fail";
        }
        // 修改绑定状态
        userBindService.notify(paramMap);
        // 给汇付宝 发起success就不会发起重试了 汇付宝
        return "success";
    }


}
